--
-- Author: yawei.zhu
-- Date: 2018-05-08 11:06:41
--
-- WeeklyTaskPanel
--

local NewRareInfoView = require("app.newBag.views.NewRareInfoView")
local DailyTaskRender = import(".renders.DailyTaskRender")

local ClassRef = app.mvc.createPanelClass(...)

local percent_1 = 52
local percent_2 = 75
local percent_3 = 100

--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.TaskDailyNode))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)

    self._weekListView = self._ui["Panel/ListView"]
    self._weekListView:removeAllItems()

    self._giftPanel1 = self._ui["Panel/Panel_top/gift_1/Panel"]  -- 引导的时候会把该node移除掉，所以这里先暂存
end

function ClassRef:refresh()
    local weeklyTasks = executeFunc(self._onOperate, "getWeeklyTasks")
    for i = 1, #weeklyTasks do
        local render = DailyTaskRender.create()
        render:onBtnClick(self._onOperate)
        render:setTaskType("weekly")
        render:setData(weeklyTasks[i])
        self._weekListView:pushBackCustomItem(render)
    end
    self._weekListView:refreshView()

    -- 设置LoadingBar初始进度为0
    local loadingBar = self._ui["Panel/Panel_top/bar/LoadingBar"]
    loadingBar:setPercent(0)
end

function ClassRef:updateWeeklyTasksShow(taskId)
    if not taskId then return end

    local taskInfo = UD:getTaskById(taskId)
    if not taskInfo then return end


    local items = self._weekListView:getItems()
    for _, item in ipairs(items) do
        if item:getData():getId() == taskId then
            item:setData(taskInfo)
            break
        end
    end
end

function ClassRef:updateWeeklyTaskProgress()
    local Panel_top = self._ui["Panel/Panel_top"]
    local progressBar = self._ui["Panel/Panel_top/bar/LoadingBar"]
    local finishedNumText = Panel_top:getChildByName("num")

       
    local totalNumber = self._onOperate("getTotalWeeklyTaskNumber")
    local finishedNumber = self._onOperate("getFinishedWeeklyTaskNumber")

    local strLimit = GD:getSystemStrPar("weeklyQuestRewardslimit")
    local arrStr = string.split(strLimit, "|")
    local value1, value2, value3 = tonumber(arrStr[1]), tonumber(arrStr[2]), tonumber(arrStr[3])

    local percent = finishedNumber / totalNumber * 100
    if finishedNumber <= value1 then
        percent = percent_1 * (finishedNumber / value1)
    elseif finishedNumber <= value2 then
        percent = percent_1 + ( percent_2 - percent_1 ) * ((finishedNumber - value1) / (value2 - value1))
    else
        percent = percent_2 + ( percent_3 - percent_2 ) * ((finishedNumber - value2) / (value3 - value2))
    end

    progressBar:setPercent(percent)
    finishedNumText:setString(finishedNumber)

    for i = 1, 3 do
        local name = "gift_" .. i
        local giftPanel

        if i == 1 then 
            giftPanel = self._giftPanel1
        else
            local giftNode = Panel_top:getChildByName(name)
            giftPanel = giftNode:getChildByName("Panel")
        end

        local maskLock = giftPanel:getChildByName("mask_lock")
        maskLock:setVisible(false)
        maskLock:setTouchEnabled(false)

        for j = 1, 3 do
            local boxName = "icon_" .. j
            local boxIcon = giftPanel:getChildByName(boxName)
            boxIcon:setVisible(false)

            boxName = "icon_".. j .. "_o"
            boxIcon = giftPanel:getChildByName(boxName)
            boxIcon:setVisible(false)
        end

        local bottomNumText = giftPanel:getChildByName("num_1")
        local getNumText = giftPanel:getChildByName("num_2")
        giftPanel:getChildByName("bg_num2"):setVisible( false )
        getNumText:setVisible( false )

        local rewardProgress = self._onOperate("getWeeklyTaskRewardProgress", tonumber(arrStr[i]))
        if rewardProgress then
            bottomNumText:setString( rewardProgress.NeedProgress )
            getNumText:setString( rewardProgress.NowProgress )

            if rewardProgress.NowProgress > 0 then -- 奖励累积次数 > 0？
                giftPanel:getChildByName("bg_num2"):setVisible( true )
                getNumText:setVisible( true )
                giftPanel:getChildByName("icon_" .. i):setVisible(true)

                local isLock = false
                if finishedNumber < tonumber(rewardProgress.NeedProgress) then -- 未解锁
                    isLock = true
                    maskLock:setVisible(true)
                end

                giftPanel:setTouchEnabled(true)
                giftPanel:addClickEventListener(function(sender)
                    local params = {}
                    params.lock = isLock
                    params.nowProgress = rewardProgress.NowProgress
                    params.needProgress = rewardProgress.NeedProgress
                    params.questType = 6
                    executeFunc(self._onOperate, "OPEN_WEEKLY_REWARD", params)
                end)
            else
                giftPanel:getChildByName("icon_"..i.."_o"):setVisible(true)
                giftPanel:setTouchEnabled(true)
                giftPanel:addClickEventListener(function(sender)end)
                giftPanel:addTouchEventListener(function(sender, eventType)
                    if eventType == ccui.TouchEventType.began then
                        local dataInfoTemp = {
                            name = L("dailyTreasureName"),
                            string1 = string.format(L("dailyTreasureDes"),S("daystartsat")),
                            string4 = L("dailyTreasureWarning"),
                        }
                        if self._rareInfoPanel then
                            self._rareInfoPanel:setData( dataInfoTemp )
                        else
                            self._rareInfoPanel = NewRareInfoView.create()
                            self._rareInfoPanel:setData( dataInfoTemp )
                            self:addChild(self._rareInfoPanel,1)
                        end
                        local triggerNodeBoundingBox = giftPanel:getBoundingBox()
                        local worldPosTemp = giftPanel:getParent():convertToWorldSpace( cc.p( triggerNodeBoundingBox.x, triggerNodeBoundingBox.y ) )
                        triggerNodeBoundingBox.x = worldPosTemp.x
                        triggerNodeBoundingBox.y = worldPosTemp.y
                        display.adjustNodePos( triggerNodeBoundingBox, self._rareInfoPanel )
                    elseif eventType == ccui.TouchEventType.ended or eventType == ccui.TouchEventType.canceled then
                        if self._rareInfoPanel then
                            self:removeChild(self._rareInfoPanel)
                            self._rareInfoPanel = nil
                        end
                    end
                end)
            end
        end
    end
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end

return ClassRef
